/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import model.dominio.Aluno;

/**
 *
 * @author ronan
 */
public class DaoAluno extends Dao {
    
    public Aluno buscarLogin (String cpf,String senha){
        EntityManager em = super.getEntityManager();
        try {
            String strSQL = "SELECT a FROM Aluno a ";
            if (cpf!= null && senha!= null) {
                strSQL += "WHERE a.cpf='" + cpf + "' AND a.senha='" + senha + "' ";
            }else{
                return null;
            }
            strSQL += "ORDER BY NOME ASC";
            em.getTransaction().begin();

            Query query = em.createQuery(strSQL);

            return (Aluno) query.getSingleResult();
        } catch (PersistenceException e) {
            return null;
        } finally {
            em.close();
        } 
    }
    
    public List<Aluno> buscarAlunos(Aluno aluno) {
        EntityManager em = super.getEntityManager();
        try {
            String strSQL = "SELECT a FROM Aluno a ";
            if (aluno.getCpf()!= null && !aluno.getCpf().equals("   .   .   -  ")) {
                strSQL += "WHERE a.cpf='" + aluno.getCpf() + "' ";
            } else if (aluno.getNome() != null) {
                strSQL += "WHERE a.nome LIKE '%" + aluno.getNome() + "%' ";
            }
            strSQL += "ORDER BY NOME ASC";
            em.getTransaction().begin();

            Query query = em.createQuery(strSQL);

            return (List<Aluno>) query.getResultList();
        } catch (PersistenceException e) {
            return null;
        } finally {
            em.close();
        }
    }
    
   
    public Aluno buscarPorCodigo(int codigo) {
        Aluno obj =new Aluno();
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            obj = em.find(obj.getClass(), codigo);
            em.getTransaction().commit();
            return obj;
        } catch (javax.persistence.PersistenceException e) {
            System.out.println(e.getMessage());
            return null;
        } finally {
            em.close();
        }
    }
 }
